﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Comissoes.Utilities;

namespace Comissoes.Models
{
    public class RegimesTributariosModel
    {
        public REGIMES_TRIBUTARIOS regime { get; set; }
        xcontEntities db = new xcontEntities();
        List<string> erros;

        public RegimesTributariosModel()
        {
            REGIMES_TRIBUTARIOS regime = new REGIMES_TRIBUTARIOS();

            this.regime = regime;
        }

        public RegimesTributariosModel(Int32? id)
        {
            this.regime = db.REGIMES_TRIBUTARIOS.FirstOrDefault(t => t.ID_RGTR == id);
        }

        public List<string> UpdateValidate(HttpRequestBase request)
        {
            this.erros = new List<string>();
            String DESC_RGTR = request["DESC_RGTR"];

            if (string.IsNullOrEmpty(request["DESC_RGTR"]))
                erros.Add("É necessário informar a descrição do regime tributário.");

            else if (db.REGIMES_TRIBUTARIOS.Any(t => t.DESC_RGTR == DESC_RGTR && t.ID_RGTR != this.regime.ID_RGTR))
                erros.Add("Já existe um regime tributário cadastrado com esta descrição no momento.");

            return erros;
        }

        public List<string> Update(HttpRequestBase request)
        {
            this.erros = new List<string>();

            try
            {
                if (db.REGIMES_TRIBUTARIOS.Any(t => t.ID_RGTR == this.regime.ID_RGTR))
                    this.regime = db.REGIMES_TRIBUTARIOS.FirstOrDefault(t => t.ID_RGTR == this.regime.ID_RGTR);

                else
                    db.AddToREGIMES_TRIBUTARIOS(this.regime);

                this.regime.DESC_RGTR = request["DESC_RGTR"];

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return erros;
        }

        public List<string> Delete()
        {
            this.erros = new List<string>();

            if (db.LOJAS.Include("REGIMES_TRIBUTARIOS").Any(t => t.REGIMES_TRIBUTARIOS.ID_RGTR == this.regime.ID_RGTR))
                erros.Add("Existem lojas cadastradas com este regime tributário no momento.");

            if (!erros.Any())
            {
                try
                {
                    db.DeleteObject(db.REGIMES_TRIBUTARIOS.FirstOrDefault(t => t.ID_RGTR == this.regime.ID_RGTR));
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    erros.Add(ex.Message);
                }
            }

            return erros;
        }
    }
}
